<?php
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Content-type: application/json');

$base64 = isset($_POST["file"]) ? $_POST["file"] : ''; // 得到参数
// print_r($base64);exit;

if (empty($base64)) {
    echo json_encode(array('code'=>400,'info'=>'没有需要上传的图片！','url'=>''));
    exit;
}
$base64 = trim($_POST["file"]); // 得到参数

$type = 'jpg';
$result = [];

$web = "http://file.szsp.zhy654.com";

$data = base64imgsave($base64);
if($data['code'] != 200){
    echo json_encode($data);
}else{
    $data['url'] =  $web.substr($data['url'], 1);
    echo json_encode($data);
}




//base64上传的图片储存到服务器本地
function base64imgsave($img){
     $basedir = "./images/".date("Y")."/".date("m")."/".date("d")."/";
//    $basedir = 'upload/base64/'.$ymd.'';
     $fullpath = $basedir;
     if(!is_dir($fullpath)){
         mkdir($fullpath,0777,true);
     }

     $types = empty($types)? array('jpg', 'gif', 'png', 'jpeg'):$types;

     $img = str_replace(array('_','-'), array('/','+'), $img);

     $b64img = substr($img, 0,100);
     if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $b64img, $matches)){//正则取出相关数据
         $type = $matches[2];
         if(!in_array($type, $types)){
             return array('code'=>400,'info'=>'图片格式不正确，只支持 jpg、gif、png、jpeg哦！','url'=>'');
         }
         $img = str_replace($matches[1], '', $img);//得到图片编码
         $img = base64_decode($img);//解码
         $photo = '/'.md5(date('YmdHis').rand(1000, 9999)).'.'.$type;
         file_put_contents($fullpath.$photo, $img);
     }else{
         $type = 'jpg';
         $img = base64_decode($img);//解码
         $photo = '/'.md5(date('YmdHis').rand(1000, 9999)).'.'.$type;
         file_put_contents($fullpath.$photo, $img);
     }

     $ary['code'] = 200;
     $ary['msg'] = '保存图片成功';
     $ary['url'] = $basedir.$photo;

     return $ary;

}
